package com.project.finance.common.cosconfig;

import com.project.finance.common.resultconfig.ResultGenerator;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Auther: 贺谋昌
 * @Date: 2019/12/4 20:58
 * @Description:
 */
@Component
public class UploadImgConfig {

    @Autowired
    COSClient cosClient;

    /**
     * @return 上传成功或失败
     */
    public boolean uploadFile(MultipartFile uploadfile, String name) throws IOException {
        try {
            // 指定要上传的文件
            final File excelFile = File.createTempFile("test", "jpg");
            uploadfile.transferTo(excelFile);
            // 指定要上传到的存储桶
            String bucketName = "farmimg-1251492284";
            // 指定要上传到 COS 上对象键
            String key = name+".jpg";
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, excelFile);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            deleteFile(excelFile);
        } catch (CosServiceException serverException) {
            serverException.printStackTrace();
            return false;
        } catch (CosClientException clientException) {
            clientException.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 删除
     *
     * @param files
     */
    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }
}
